<template>
  <div class="container">
    <el-main>
      <!-- Upload Log Form -->
      <div v-if="selected === 'uploadLog'">
        <h2>上传日志</h2>
      </div>

      <!-- Repair Records -->
      <div v-else-if="selected === 'repairRecords'">
        <el-table
          v-loading="listLoading"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
        >
          <el-table-column align="center" label="序号" wreserve-idth="95">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="申请时间" width="160">
            <template slot-scope="scope">
              <span>{{ scope.row.reserveTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="申请理由" align="center">
            <template slot-scope="scope">
              {{ scope.row.reserveDescribe }}
            </template>
          </el-table-column>
          <el-table-column
            class-name="status-col"
            label="审核状态"
            width="110"
            align="center"
          >
            <template slot-scope="scope">
              <!-- 审核状态标签 -->
              <el-tag :type="getColor(scope.row.reserveState)">
                {{ scope.row.reserveState | reserveStateFilter }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            prop="created_at"
            label="操作"
            width="250"
          >
            <template slot-scope="scope">
              <!-- 使用 flex 布局将所有操作放置在同一行 -->
              <div class="action-row">
                <!-- 查看按钮 -->
                <el-button
                  type="primary"
                  round
                  size="mini"
                  @click="editRecord(scope.row)"
                >查看</el-button>
                <div v-if="['CANCEL', 'AGREE', 'DISAGREE', 'AGREE_R'].includes(scope.row.reserveState)">
                  <!-- 提示信息 -->
                  <el-alert
                    :title="getAlertMessage(scope.row.reserveState)"
                    type="info"
                    show-icon
                    :closable="false"
                    style="margin-bottom: 0; margin-left: 5px;"
                  />
                </div>
                <div v-else>
                  <el-button
                    type="danger"
                    round
                    size="mini"
                    @click="deleteRecord(scope.row)"
                  >取消预约
                  </el-button>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- View/Edit Record Dialog -->
        <el-dialog
          :trouble-describe="dialogTitle"
          :visible.sync="dialogVisible"
          wreserve-idth="60%"
        >
          <el-form
            ref="currentRecord"
            :model="currentRecord"
            label-width="120px"
          >
            <el-form-item label="申请单位">
              <el-input v-model="currentRecord.applyUnit" />
            </el-form-item>
            <el-form-item label="人数">
              <el-input
                v-model.number="currentRecord.peopleCount"
              />
            </el-form-item>
            <el-form-item label="使用时间">
              <el-input v-model="currentRecord.reserveTime" />
            </el-form-item>
            <el-form-item label="使用软件">
              <el-input v-model="currentRecord.software" />
            </el-form-item>
            <el-form-item label="负责人">
              <el-input v-model="currentRecord.principal" />
            </el-form-item>
            <el-form-item label="联系方式">
              <el-input v-model="currentRecord.contact" />
            </el-form-item>
            <el-form-item label="申请事由">
              <el-input
                v-model="currentRecord.reserveDescribe"
                type="textarea"
              />
            </el-form-item>
            <el-form-item label="申请保证">
              <el-input
                v-model="currentRecord.guarantee"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
                placeholder="申请保证内容"
                disabled
              />
              <el-checkbox v-model="checked">同意并遵守规则</el-checkbox>
            </el-form-item>
            <!-- 辅导员或指导老师意见和实验中心审核意见可以视情况添加 -->
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">关闭</el-button>
          </div>
        </el-dialog>

      </div>
    </el-main>
  </div>
</template>

<script>
import { UserInquiryAppointment, UserDelAppointment } from '@/api/jifang'
import { getId } from '@/utils/auth' // get token from cookie
export default {
  filters: {
    reserveStateFilter(reserveState) {
      const reserveStateMap = {
        AGREE: '已同意(预约)',
        DISAGREE: '已拒绝(申请)',
        AGREE_R: '已拒绝(取消)',
        CANCEL: '已取消',
        WAIT_AGREE: '待审核(申请)',
        WAIT_CANCEL: '待审核(取消)'
      }
      return reserveStateMap[reserveState]
    }
  },
  data() {
    return {
      selected: 'repairRecords', // Initially selected option
      logForm: {
        name: '',
        reserveId: '',
        contact: '',
        department: '',
        deviceName: '',
        deviceLocation: '',
        issueDescription: '',
        issueTime: '',
        preOperation: '',
        issueType: []
        // Add more fields as needed
      },
      list: null,
      listLoading: true,
      dialogVisible: false,
      dialogTitle: '',
      reservationForm: {
        applyUnit: '',
        peopleCount: '',
        useTime: {
          startDate: '',
          endDate: ''
        },
        software: '',
        principal: '',
        contact: '',
        reserveDescribe: '',
        guarantee:
            '我代表申请单位做出保证：在机房使用期间，对活动参与者的人身安全负责，在使用前对准备进入实验室的人员进行用电安全提醒，同时对实验室内设备财务安全负责，爱护使用机房内仪器设备，如有丢失照价赔偿。活动结束后做好活动记录并向实验中心交回申请表；同时负责清理现场，保证实验室清洁；全部人员离开实验室时关好门窗如不能做到则接受实验中心不再受理本单位以后使用实验室的任何申请的处分。'
        // 其他需要的字段...
      },
      checked: true,
      currentRecord: {
        reserveId: '',
        reservePlace: '',
        reserveer: '',
        reserveTime: '',
        reserveDevice: '',
        troubleDescribe: '',
        reserveState: '',
        applyUnit: '410基地',
        peopleCount: '10',
        software: 'DEV C++',
        principal: '石伟凡',
        contact: '13483096792',
        guarantee:
            '我代表申请单位做出保证：在机房使用期间，对活动参与者的人身安全负责，在使用前对准备进入实验室的人员进行用电安全提醒，同时对实验室内设备财务安全负责，爱护使用机房内仪器设备，如有丢失照价赔偿。活动结束后做好活动记录并向实验中心交回申请表；同时负责清理现场，保证实验室清洁；全部人员离开实验室时关好门窗如不能做到则接受实验中心不再受理本单位以后使用实验室的任何申请的处分。'
      }
    }
  },
  created() {
    this.listLoading = true
    this.list = []
    this.listLoading = false
    const userId = getId('userId')
    UserInquiryAppointment(userId)
      .then(res => {
        this.list = res.data
        this.listLoading = false
      })
      .catch(error => {
        console.error(error)
      })
  },
  methods: {
    getAlertMessage(state) {
      const messages = {
        CANCEL: '该预约已取消',
        AGREE: '已同意“该预约”申请',
        DISAGREE: '已拒绝“该预约”申请',
        AGREE_R: '已拒绝“取消预约”申请'
      }
      return messages[state] || '未知状态'
    },
    getColor(reserveState) {
      switch (reserveState) {
        case 'AGREE':
          return 'success'
        case 'DISAGREE':
        case 'AGREE_R':
          return 'danger'
        case 'CANCEL':
          return 'info'
        case 'WAIT_AGREE':
        case 'WAIT_CANCEL':
          return 'warning'
        default:
          return ''
      }
    },
    formatDate(dateString) {
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    handleSelect(selected) {
      this.selected = selected
    },
    deleteRecord(record) {
      UserDelAppointment(record.reserveId)
        .then(res => {
          UserInquiryAppointment(record.userId)
            .then(res => {
              this.list = res.data
              this.listLoading = false
            })
            .catch(error => {
              console.error(error)
            })
          this.$message({
            type: 'success',
            message: res.message
          })
        })
        .catch(error => {
          console.error(error)
        })
      // setTimeout(() => {
      //   // location.reload()
      //   console.log('500ms后执行的方法')
      // }, 500)
    },
    editRecord(record) {
      this.dialogTitle = '编辑预约记录'
      this.currentRecord = { ...record } // Make a copy to avoid modifying the original record directly
      console.log(this.currentRecord)
      // this.currentRecord.applyUnit = '410基地',
      this.currentRecord.peopleCount = '50'
      // 随机选择一个基地、班级或社团
      this.currentRecord.applyUnit = '315基地'
      // 随机选择一个软件
      this.currentRecord.software = 'mysql'
      // 随机生成一个三个字的人名，这里使用一个假设的数组，您需要根据实际情况来创建或获取这样的人名列表
      this.currentRecord.principal = '石伟凡'
      this.currentRecord.contact = '13483096792'
      // 随机生成一个11位的联系电话，这里简单地在现有号码前加一个随机的前缀
      this.currentRecord.guarantee = '我代表申请单位做出保证：在机房使用期间，对活动参与者的人身安全负责，在使用前对准备进入实验室的人员进行用电安全提醒，同时对实验室内设备财务安全负责，爱护使用机房内仪器设备，如有丢失照价赔偿。活动结束后做好活动记录并向实验中心交回申请表；同时负责清理现场，保证实验室清洁；全部人员离开实验室时关好门窗如不能做到则接受实验中心不再受理本单位以后使用实验室的任何申请的处分。'
      this.dialogVisible = true
    }
  }
}
</script>

  <style scoped>
  .el-divreserveIder {
  margin: 20px 0;
}
.action-row {
  display: flex;
  align-items: center;
}
.action-row > * {
  margin-left: 5px; /* 根据需要调整间距 */
}
  .container {
    display: flex;
    height: 100vh; /* Full height */
  }

  .el-asreserveIde {
    background-color: #f0f2f5;
  }

  .el-main {
    padding: 20px;
  }

  .el-divreserveIder {
    margin: 20px 0;
  }
  </style>
